package com.medvalley.tcm.service.impl;

import com.google.common.collect.Lists;
import com.medvalley.tcm.base.BusinessException;
import com.medvalley.tcm.dao.*;
import com.medvalley.tcm.domain.*;
import com.medvalley.tcm.vo.outputvo.MusicOutputVo;
import com.medvalley.tcm.vo.outputvo.MyCheckMusicItemOutputVo;
import com.medvalley.tcm.vo.outputvo.MyCheckMusicOutputVo;
import com.medvalley.tcm.vo.outputvo.MyMusicOutputVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

import static com.medvalley.tcm.base.QuestionType.*;

@Service
@Slf4j
public class MyMusicService {

    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private MyFavoriteMusicDao myFavoriteMusicDao;
    @Autowired
    private MusicDao musicDao;

    @Autowired
    private MyRecommendMusicDao recommendMusicDao;

    @Autowired
    private MindQuestionnaireDao mindQuestionnaireDao;

    @Autowired
    private QuestionnaireDao questionnaireDao;

    public void addMyMusic(long userId, int musicId) {
        MyFavoriteMusic myFavoriteMusicDB = myFavoriteMusicDao.findOneByMusicIdAndUserId(musicId, userId);
        if (myFavoriteMusicDB != null) {
            throw new BusinessException("已经添加过，请不要重复添加");
        }
        MyFavoriteMusic myFavoriteMusic = new MyFavoriteMusic();
        myFavoriteMusic.setMusicId(musicId);
        myFavoriteMusic.setUserId(userId);
        myFavoriteMusicDao.save(myFavoriteMusic);
    }

    public void deleteFromMyMusic(int musicId, long userId) {
        MyFavoriteMusic myFavoriteMusic = myFavoriteMusicDao.findOneByMusicIdAndUserId(musicId, userId);
        if (myFavoriteMusic == null) {
            throw new BusinessException("此音乐不属于你");
        }
        myFavoriteMusicDao.deleteById(myFavoriteMusic.getId());

    }

    public List<MyMusicOutputVo> listMyMusic(long userId) {
        List<MyMusicOutputVo> myMusicOutputVoList = Lists.newArrayList();
        List<MyFavoriteMusic> myFavoriteMusicList = myFavoriteMusicDao.findAllByUserId(userId);

        if (!CollectionUtils.isEmpty(myFavoriteMusicList)) {
            List<Integer> musicIds = myFavoriteMusicList.stream().map(MyFavoriteMusic::getMusicId).collect(Collectors.toList());
            List<Music> musicList = musicDao.findAllByIdIn(musicIds);
            if (!CollectionUtils.isEmpty(musicList)) {
                musicList.forEach(m -> {
                    MyMusicOutputVo myMusicOutputVo = new MyMusicOutputVo();
                    myMusicOutputVo.setMusicId(m.getId());
                    BeanUtils.copyProperties(m, myMusicOutputVo);
                    myMusicOutputVoList.add(myMusicOutputVo);
                });
            }
        }
        return myMusicOutputVoList;
    }

    public MyCheckMusicOutputVo recommendMusic(String userPhone) {
        MyCheckMusicOutputVo myCheckMusicOutputVo = new MyCheckMusicOutputVo();
        UserInfo userInfo = userInfoDao.findOneByPhone(userPhone);
        long userId = userInfo.getId();
        log.info("user:{}-{} get recommend music ", userId, userPhone);
        MyCheckMusicItemOutputVo bodyCheck = new MyCheckMusicItemOutputVo();
        MyCheckMusicItemOutputVo mindCheck = new MyCheckMusicItemOutputVo();
        MyCheckMusicItemOutputVo subhealthyCheck = new MyCheckMusicItemOutputVo();
        MyCheckMusicItemOutputVo psychologyCheck = new MyCheckMusicItemOutputVo();
        MyCheckMusicItemOutputVo insomniaCheck = new MyCheckMusicItemOutputVo();

        // 体质推荐
        List<MyRecommendMusic> bodyRecommendMusicList = recommendMusicDao.findAllByUserIdAndCheckType(userId, 11);// 体质辨识
        bodyCheck.setMusicOutputVoList(generateRecommend(bodyRecommendMusicList));
        List<Questionnaire> questionnaires = questionnaireDao.getOneByUserNumberAndSrcOrderByIdDesc(userPhone, "app");
        if (!CollectionUtils.isEmpty(questionnaires)) {
            Questionnaire q = questionnaires.get(0);
            bodyCheck.setCheckDate(DateFormatUtils.format(q.getCreateTime(), "yyyy-MM-dd"));
            bodyCheck.setCheckResult(q.getConfirm());
        }
        myCheckMusicOutputVo.setBodyCheck(bodyCheck);
        // 焦虑推荐
        List<MyRecommendMusic> mindRecommendMusicList = recommendMusicDao.findAllByUserIdAndCheckType(userId, ANXIETY.getCode());// 焦虑
        mindCheck.setMusicOutputVoList(generateRecommend(mindRecommendMusicList));
        List<MindQuestionnaire> jlMindQuestionnaireList = mindQuestionnaireDao.findAllByPhoneAndTypeOrderByIdDesc(userPhone, ANXIETY.getCode());
        if (!CollectionUtils.isEmpty(jlMindQuestionnaireList)) {
            MindQuestionnaire mindQuestionnaire = jlMindQuestionnaireList.get(0);
            mindCheck.setCheckDate(DateFormatUtils.format(mindQuestionnaire.getCreateTime(), "yyyy-MM-dd"));
            mindCheck.setCheckResult(mindQuestionnaire.getResult());
        }
        myCheckMusicOutputVo.setMindCheck(mindCheck);
        // 抑郁推荐
        List<MyRecommendMusic> subhealthyRecommendMusicList = recommendMusicDao.findAllByUserIdAndCheckType(userId, DEPRESSION.getCode());// 抑郁
        subhealthyCheck.setMusicOutputVoList(generateRecommend(subhealthyRecommendMusicList));
        List<MindQuestionnaire> yyMindQuestionnaireList = mindQuestionnaireDao.findAllByPhoneAndTypeOrderByIdDesc(userPhone, DEPRESSION.getCode());
        if (!CollectionUtils.isEmpty(yyMindQuestionnaireList)) {
            MindQuestionnaire mindQuestionnaire = yyMindQuestionnaireList.get(0);
            subhealthyCheck.setCheckDate(DateFormatUtils.format(mindQuestionnaire.getCreateTime(), "yyyy-MM-dd"));
            subhealthyCheck.setCheckResult(mindQuestionnaire.getResult());
        }
        myCheckMusicOutputVo.setSubhealthyCheck(subhealthyCheck);

        // 心理压力推荐
        List<MyRecommendMusic> psychologyRecommendMusicList = recommendMusicDao.findAllByUserIdAndCheckType(userId, XINLI.getCode());// 心理压力
        psychologyCheck.setMusicOutputVoList(generateRecommend(psychologyRecommendMusicList));
        List<MindQuestionnaire> xlylQuestionList = mindQuestionnaireDao.findAllByPhoneAndTypeOrderByIdDesc(userPhone, XINLI.getCode());
        if (!CollectionUtils.isEmpty(xlylQuestionList)) {
            MindQuestionnaire mindQuestionnaire = xlylQuestionList.get(0);
            psychologyCheck.setCheckDate(DateFormatUtils.format(mindQuestionnaire.getCreateTime(), "yyyy-MM-dd"));
            psychologyCheck.setCheckResult(mindQuestionnaire.getResult());
        }
        myCheckMusicOutputVo.setPsychologyCheck(psychologyCheck);

        // 失眠推荐
        List<MyRecommendMusic> insomniaRecommendMusicList = recommendMusicDao.findAllByUserIdAndCheckType(userId, SHIMIAN.getCode());// 失眠
        List<MindQuestionnaire> smQuestionList = mindQuestionnaireDao.findAllByPhoneAndTypeOrderByIdDesc(userPhone, SHIMIAN.getCode());
        insomniaCheck.setMusicOutputVoList(generateRecommend(insomniaRecommendMusicList));
        if (!CollectionUtils.isEmpty(smQuestionList)) {
            MindQuestionnaire mindQuestionnaire = smQuestionList.get(0);
            insomniaCheck.setCheckDate(DateFormatUtils.format(mindQuestionnaire.getCreateTime(), "yyyy-MM-dd"));
            insomniaCheck.setCheckResult(mindQuestionnaire.getResult());
        }
        myCheckMusicOutputVo.setInsomniaCheck(insomniaCheck);

        return myCheckMusicOutputVo;
    }

    private List<MusicOutputVo> generateRecommend(List<MyRecommendMusic> recommendMusicList) {
        List<MusicOutputVo> musicOutputVoList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(recommendMusicList)) {
            recommendMusicList.forEach(r -> {
                MusicOutputVo musicOutputVo = new MusicOutputVo();
                musicOutputVo.setId(r.getMusicId());
                musicOutputVo.setMusicName(r.getMusicName());
                musicOutputVo.setMusician(r.getMusician());
                musicOutputVo.setMusicUrl(r.getMusicUrl());
                musicOutputVo.setMusicDuration(r.getMusicDuration());
                musicOutputVo.setCateId(r.getCatId());
                musicOutputVo.setCateName(r.getCatName());
                musicOutputVoList.add(musicOutputVo);
            });
        }
        return musicOutputVoList;
    }

}
